package com.biwin.common.app.exception;

import com.biwin.common.api.constant.BwSystemConstant;
import com.biwin.common.api.enums.IBwEnum;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author biwin
 * @since 0.0.1
 */
public class BwBasicException extends RuntimeException {

    /**
     * 错误码
     */
    private String errorCode;

    /**
     * 错误信息
     */
    private String errorMessage;

    /**
     * 导致当前错误的请求参数
     */
    private volatile Map<String, Object> requestParams = new HashMap<>();

    public BwBasicException(String errorCode, String errorMessage) {
        super(errorMessage);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public BwBasicException(String errorCode, String errorMessage, Map<String, Object> requestParams) {
        super(errorMessage);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
        this.requestParams = requestParams;
    }

    public BwBasicException(IBwEnum basicExceptionEnum, String... formatMessage) {
        super(basicExceptionEnum.getValue());
        this.errorCode = basicExceptionEnum.getCode();
        this.errorMessage = basicExceptionEnum.getValue();
        if (errorMessage.contains(BwSystemConstant.PERCENT)) {
            this.errorMessage = String.format(this.errorMessage, (Object) formatMessage);
        } else {
            StringBuilder sb = new StringBuilder(this.errorMessage);
            for (String msg : formatMessage) {
                sb.append(msg);
            }
            this.errorMessage = sb.toString();
        }
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public Map<String, Object> getRequestParams() {
        return requestParams;
    }

    public BwBasicException setRequestParams(String key, Object value) {
        this.requestParams.put(key, value);
        return this;
    }

    public BwBasicException setRequestParams(Map<String, Object> requestParams) {
        this.requestParams.putAll(requestParams);
        return this;
    }
}
